import { ref, reactive } from "vue";
import { updatePassword } from "@/api/manager";
import { toast } from "@/composables/utils";
import { logout } from "@/api/manager";
import { removeToken } from "@/composables/auth";
import { showModal } from "@/composables/utils";
import router from "@/router/index";
import { useUserStore } from "@/stores";

// 定义 useRepassword 函数
export const useRepassword = () => {
  const formDrawerRef = ref(null);

  const formRef = ref();

  const form = reactive({
    oldpassword: "",
    password: "",
    repassword: "",
  });

  const rules = {
    oldpassword: [
      { required: true, message: "旧密码不能为空", trigger: "blur" },
      { min: 6, max: 20, message: "密码长度在6-20位", trigger: "blur" },
    ],
    password: [
      { required: true, message: "新密码不能为空", trigger: "blur" },
      { min: 6, max: 20, message: "密码长度在6-20位", trigger: "blur" },
    ],
    repassword: [
      { required: true, message: "确认密码不能为空", trigger: "blur" },
      { min: 6, max: 20, message: "密码长度在6-20位", trigger: "blur" },
    ],
  };

  const onSubmitForm = () => {
    formRef.value.validate((valid, fields) => {
      if (!valid) {
        return false;
      }
      formDrawerRef.value.showLoading();
      updatePassword(form)
        .then((res) => {
          toast("修改密码成功，请重新登录");
          removeToken();
          router.push("/login");
        })
        .catch((error) => {
          toast("修改密码失败，请重试");
        })
        .finally(() => {
          formDrawerRef.value.hideLoading();
        });
    });
  };

  const openRepasswordForm = () => {
    formDrawerRef.value.open();
  };

  return {
    formDrawerRef,
    formRef,
    rules,
    form,
    onSubmitForm,
    openRepasswordForm,
  };
};

// 定义 useLogout 函数
export const useLogout = () => {
  const userStore = useUserStore();
  const handleLogout = () => {
    showModal("是否要退出登录?").then((res) => {
      console.log("退出登录");
      logout().finally(() => {
        removeToken();
        router.push("/login");
        userStore.removeUser();
        toast("退出登录成功!");
      });
    });
  };

  return { handleLogout };
};
